# -*- coding: utf-8 -*-
import re
import requests
import subprocess
import json


# ##########################################
# 主程序开始
# ##########################################
# 定义查询的日期
# 定义更新的报关单数量
# 使用cookie
# 登录信息
index_url= 'http://www.npedi.com/ediportal-web/ediweb/index.jsp'
# <img border=0 src="/edi/ediweb/image.jsp">
# <img id="img" border=0 src="/edi/ediweb/jcaptcha.jpg" onclick="refresh();" alt="点击更换验证码"/>
# pic1_pattern = 'src="/edi/ediweb/image.jsp"'
# pic2_pattern = 'src="/edi/ediweb/jcaptcha.jpg"'
# pic_url1 = 'http://www.npedi.com/edi/ediweb/image.jsp'
# pic_url2 = 'http://www.npedi.com/edi/ediweb/jcaptcha.jpg'
pic_url = 'http://www.npedi.com/ediportal-web/createCheckImages.action'

# http://www.npedi.com/ediportal-web/loginSystem.action?userId=GUEST&password=guest&checkCode=1042
login_url = 'http://www.npedi.com/ediportal-web/loginSystem.action'
auth_url = 'http://127.0.0.1:50003/auth_npedi'
check_url = 'http://www.npedi.com/ediportal-web/userLoginStatus.action'
# index_url='http://www.npedi.com/edi/ediweb/index.jsp'
post_data = dict()
post_data['userId'] = 'GUEST'
post_data['password'] = 'guest'
post_data['checkCode'] = ''
# post_data['x'] = '0'
# post_data['y'] = '0'
login_pattern = '{"userId":"GUEST","userName":"GUEST"}'
cookies = ''
code = ''
SESSION_ID_IN_BIZ=''
JSESSIONID=''

# 登录的地址

def getcookie():
    global cookies
    r = requests.get(index_url)
    print 'getcookie:',r.cookies
    cookies= r.cookies

def randcode(pic):
    with open('checkimages.jpg', 'wb') as f1:
        f1.write(pic)
    subprocess.call('tesseract.exe checkimages.jpg checkimages digits')
    with open('checkimages.txt') as f2:
        t = f2.read()
    print 'txt:', t
    t = re.findall('\d', t)
    if len(t) == 4:
        return ''.join(t)
    else:
        return ''

def getpic(url):
    global cookies, code
    r = requests.get(url,cookies=cookies)
    code = randcode(r.content)
    # cookies = r.cookies
    # print cookies


def gethtml(url, params):
    # post_data['randcode']=''
    # url='%s?userId=%s&password=%s&checkCode=%s'%(url,params['userId'],params['password'],params['checkCode'])
    global cookies,SESSION_ID_IN_BIZ
    print url
    login_html = requests.post(url, params=params, cookies=cookies)
    print login_html.cookies
    if login_html.cookies:
        print login_html.cookies['SESSION_ID_IN_BIZ']
        SESSION_ID_IN_BIZ=login_html.cookies['SESSION_ID_IN_BIZ']
    else:
        print 'SESSION_ID_IN_BIZ not exits'
    return login_html.text


def checkhtml(url, params):
    h = gethtml(url, params)
    print h
    try:
        s=json.loads(h)['userId']
        print s,'success'
        return True
    except:
        print 'login fail'
        return False


def savecookie(url, cookie):
    data = {'cookie': cookie, 'site': 'npedi.new', 'action': 'remote'}
    headers = {'Accept': 'application/json'}
    r = requests.post(url, data=data, headers=headers)
    print r.text


def refresh(url):
    params = {'site': 'npedi.new', 'action': 'remote'}
    headers = {'Accept': 'application/json'}
    auth = requests.get(auth_url, params=params, headers=headers).json()
    print 'auth:',auth
    l_cookie=auth['cookie'].split(';')
    if len(l_cookie)==2:
        cookies=dict(JSESSIONID=l_cookie[0],SESSION_ID_IN_BIZ=l_cookie[1])
    else:
        cookies=dict(JSESSIONID=l_cookie[0])
    
    return requests.get(url, cookies=cookies).text if auth['result'] else ''

result = refresh(check_url)
print result
status=json.loads(result)['status']

if status=='y':
    print json.loads(result)['userId']
else:
    print 'session expired'
    while not checkhtml(login_url, post_data):
        getcookie()
        getpic(pic_url)
        post_data['checkCode'] = code
        print post_data['checkCode'], cookies
    savecookie(auth_url, '%s;%s'%(cookies['JSESSIONID'],SESSION_ID_IN_BIZ))
    
    
    
# if re.search(login_pattern, html):
    # print 'session alive'
# else:
    # print 'session expired'
    # while not checkhtml(login_url, post_data):
        # getcookie()
        # getpic(pic_url)
        # post_data['checkCode'] = code
        # print post_data['checkCode'], cookies
    # savecookie(auth_url, cookies['JSESSIONID'])
